package org.geoserver.jtilecache.service;

import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.geoserver.jtilecache.util.Configuration;

public class Request {

	private static Log log = LogFactory.getLog(org.geoserver.jtilecache.service.Request.class);

	private URL server = null;
	private Parameters params = null;

	public Request() {
		this.setServerFromConfiguration();
		this.setParametersFromConfiguration();
	}

	public Request(URL server) {
		this.setServer(server);
		this.setParametersFromConfiguration();
	}

	public Request(String url) {
		this.setServer(url);
		this.setParametersFromConfiguration();
	}

	public Request(Parameters params) {
		this.setServerFromConfiguration();
		this.setParametersFromConfiguration();
		this.params.merge(params);
	}

	public Request(String server, Parameters params) {
		this.setServer(server);
		this.setParametersFromConfiguration();
		this.params.merge(params);
	}

	public Request(URL server, Parameters params) {
		this.setServer(server);
		this.setParametersFromConfiguration();
		this.params.merge(params);
	}

	/**
	 * set server address based on configuration
	 */
	private void setServerFromConfiguration() {
		Configuration config = Configuration.getInstance();
		this.setServer(config.getServer());
	}

	/**
	 * set parameters based on configuration
	 */
	private void setParametersFromConfiguration() {
		Configuration config = Configuration.getInstance();
		this.setParameters(config.getParameters());
	}

	/**
	 * @return the address URL
	 */
	public URL getServer() {
		return server;
	}

	/**
	 * @param address the address URL to set
	 */
	public void setServer(URL server) {
		this.server = server;
	}

	public void setServer(String address) {
		try {
			this.server = new URL(address);
		} catch(MalformedURLException mue) {
			log.error("Invalid server URL String: ", mue);
			// Do nothing, leave this.server set to previous value
		}
	}

	public Parameters getParameters() {
		return params;
	}

	public void setParameters(Parameters params) {
		this.params = params;
	}

	public URL getURL() {
		URL address = null;
		try {
			address = new URL(this.server.toExternalForm() + this.params.getURLString());
			log.debug("url: " + address);
		} catch(MalformedURLException mue) {
			log.error("Invalid URL from server and parameters: ", mue);
		}
		return address;
	}

	public String toString() {
		return getURL().toString();
	}

}
